//
//  ORInformationViewController.m
//  News
//
//  Created by rimi on 2016/12/8.
//  Copyright © 2016年 dongfumei. All rights reserved.
//

#import "ORInformationViewController.h"
#import "ORInformationTableViewCell.h"
#import "OREditorViewController.h"
#import "ORAccountHeadImage.h"

@interface ORInformationViewController () <UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic, strong) UITableView *tableView;
//背景
@property (nonatomic, strong) UIImageView *backImage;
//头像
@property (nonatomic, strong) UIImageView *headImage;
//名字
@property (nonatomic, strong) UILabel *nameLabel;
//编辑
@property (nonatomic, strong) UIButton *editorButton;
//
@property (nonatomic, strong) UIVisualEffectView *effectView;
@property (nonatomic, strong) ORAccountHeadImage *accountHead;

@end

@implementation ORInformationViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
}

- (void)initUI{
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"个人信息";
    [self.view addSubview:self.backImage];
    //模糊效果
    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    _effectView = [[UIVisualEffectView alloc] initWithEffect:blur];
    _effectView.frame = self.backImage.bounds;
    _effectView.alpha = 0;
    //    _effectView.backgroundColor = [UIColor redColor];
    
    if ([ORUserSingleton sharedUserInfo].isLogin) {
        
        [self.headImage sd_setImageWithURL:[NSURL URLWithString:[ORUserSingleton sharedUserInfo].headImageUrl] ];
        [self.backImage sd_setImageWithURL:[NSURL URLWithString:[ORUserSingleton sharedUserInfo].headImageUrl] ];
        _effectView.alpha = 0.6;
        UITapGestureRecognizer *headTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapGesture)];
        [self.headImage addGestureRecognizer:headTap];
        
    }else{
        _effectView.alpha = 0;
    }
    [self.backImage addSubview:self.effectView];
    [self.backImage addSubview:self.headImage];
    [self.effectView addSubview:self.nameLabel];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.editorButton];
    self.tableView.scrollEnabled = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)alertWithTitle:(NSString *)title Message:(NSString *)message buttonBlock:(void(^)(void))block {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if (block) {
            block();
        }
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
    
}

#pragma mark - @selector

- (void)editor:(UIButton *)sender{
    
    if ([ORUserSingleton sharedUserInfo].isLogin) {
        OREditorViewController *editor = [[OREditorViewController alloc]init];
        [self.navigationController pushViewController:editor animated:YES];
    }else{
        sender.userInteractionEnabled = NO;
    }
    
}

#pragma mark - 照相机&&相册

- (void)tapGesture{
    
    //初始化提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //按钮：从相册选择，类型：UIAlertActionStyleDefault
    [alert addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //初始化UIImagePickerController
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        //获取方式1：通过相册（呈现全部相册）,UIImagePickerControllerSourceTypePhotoLibrary
        //获取方式2：通过相机，UIImagePickerControllerSourceTypeCamera
        //获取方式3：通过相册（呈现全部图片），UIImagePickerControllerSourceTypeSavedPhotosAlbum
        PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //允许编辑，即放大剪裁
        PickerImage.allowsEditing = YES;
        //自代理
        PickerImage.delegate = self;
        //页面跳转
        [self presentViewController:PickerImage animated:YES completion:nil];
    }]];
    
    //按钮：拍照，类型：UIAlertActionStyleDefault
    
    [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //通过相机的方式
        
        if (![UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceFront]) {
            
            return;
        }

        
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        //获取方式：通过相机
        PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
        PickerImage.allowsEditing = YES;
        PickerImage.delegate = self;
        [self presentViewController:PickerImage animated:YES completion:nil];
    }]];
    
    //按钮：取消，类型：UIAlertActionStyleCancel
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
    
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //定义一个newPhoto,用来存放我们选择的图片
    UIImage *newPhoto = info[UIImagePickerControllerEditedImage];
    
    
    self.headImage.image = newPhoto;
    self.backImage.image = newPhoto;
    [self dismissViewControllerAnimated:YES completion:nil];
    
    if (newPhoto) {
        AVUser *user = [AVUser currentUser];
        //图片转化成数据流
        NSData *data = UIImageJPEGRepresentation(newPhoto, 0.5);
        AVFile *file = [AVFile fileWithData:data];
        [user setObject:file forKey:@"headImage"];
        [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
            if (succeeded) {
                
                if (error) {
                    [self alertWithTitle:@"" Message:@"网络出现一点问题！头像修改失败！" buttonBlock:nil];
                    return ;
                }
                [ORUserSingleton sharedUserInfo].headImageUrl = file.url;
                
            } else {
                
            }
        }];
        
    }
}

#pragma mark - UITableViewDelegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString *reuseIdentifier = @"UITableViewCell";
    ORInformationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    
    if (!cell) {
        cell = [[ORInformationTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
    }
    NSArray *array = @[@"账号:",@"昵称:",@"性别:"];
    cell.textLabel.text = array[indexPath.row];
    if (indexPath.row == 0) {
        cell.informationLabel.text = [ORUserSingleton sharedUserInfo].username;
    }else if (indexPath.row == 1){
        cell.informationLabel.text = [ORUserSingleton sharedUserInfo].accountName;
    }else if (indexPath.row == 2){
        cell.informationLabel.text = [ORUserSingleton sharedUserInfo].accounsex;
    }
    
    cell.selectionStyle = UITableViewCellEditingStyleNone;
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return @"个人资料";
}

#pragma mark - getter

- (UIImageView *)backImage{
    if (!_backImage) {
        _backImage = [[UIImageView alloc]initWithFrame:AAdaptionRect(0, 0, kBaseWidth, 250)];
        _backImage.image = [UIImage imageNamed:@"NEWS"];
        //开启交互
        _backImage.userInteractionEnabled = YES;
    }
    return _backImage;
}

- (UIImageView *)headImage{
    if (!_headImage) {
        _headImage = [[UIImageView alloc]initWithFrame:AAdaptionRect(kBaseWidth/2-45, 85, 90, 90)];
        _headImage.layer.cornerRadius = AAdaptation(45);
        _headImage.layer.masksToBounds = YES;
         //开启交互
        _headImage.userInteractionEnabled = YES;
    }
    return _headImage;
}

- (UILabel *)nameLabel{
    if (!_nameLabel) {
        _nameLabel = [[UILabel alloc]initWithFrame:AAdaptionRect(kBaseWidth/2-100, CGRectGetMaxY(self.headImage.frame)/AAdaptationWidth()+20, 200, 30)];
        _nameLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _nameLabel;
}

- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:AAdaptionRect(0, CGRectGetMaxY(self.backImage.frame)/AAdaptationWidth(), kBaseWidth, 150/AAdaptationWidth()) style:UITableViewStylePlain];
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.scrollEnabled = NO;
    }
    return _tableView;
}

- (UIButton *)editorButton{
    if (!_editorButton) {
        _editorButton = [[UIButton alloc]initWithFrame:AAdaptionRect(0, 0, 350, 44)];
        _editorButton.center = AAadaptationPoint(kBaseWidth/2, CGRectGetMaxY(self.tableView.frame)/AAdaptationWidth()+100);
        [_editorButton setTitle:@"编   辑" forState:UIControlStateNormal];
        [_editorButton addTarget:self action:@selector(editor:) forControlEvents:UIControlEventTouchUpInside];
                _editorButton.backgroundColor = MainColor;
        _editorButton.layer.cornerRadius = 3;
        _editorButton.layer.masksToBounds = YES;
    }
    return _editorButton;
}

- (ORAccountHeadImage *)accountHead{
    if (!_accountHead) {
        _accountHead = [[ORAccountHeadImage alloc]init];
    }
    return _accountHead;
}

@end
